<template>
  <!-- 购物车头部组件 -->
  <div id="CartTop">
    <catrtop />
  </div>
  <div style="display: flex; flex-direction: column; align-items: center;" id="Catalog">
    <table  style="width: 60%; background-color: #e9e9e9; border-collapse: collapse;" class="table-container">
      <tbody>   
         <tr>   
          <td style="font-weight: bold; border: 1px solid white;text-align: left;font-size: 25px;"
          colspan="2">
            Payment Details
          </td>
        </tr>
        <tr>   
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            CartType
          </td>
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            <select name="cartType" id="cartType" style="font-size: 25px;" v-model="form.cardType">
              <option value="Visa">Visa</option>
              <option value="wishlist">Wishlist</option>
            </select>
          </td>
        </tr>

         <tr>   
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            Cartnumber:
          </td>
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            <input type="text" name="cartNumber" id="cartNumber" placeholder="Use a fake number"
            style="font-size: 25px;" v-model="form.creditCard">
          </td>
        </tr>


        <tr>   
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            Expiry Date:
          </td>
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
           <input type="text" name="expiryDate" id="expiryDate" placeholder="MM/YY" style="font-size: 25px;"
           v-model="form.expireDate">
          </td>
        </tr>


        <tr>   
          <td style="font-weight: bold; border: 1px solid white;text-align: left;font-size: 25px;"
          colspan="2">
            Billing Address
          </td>
        </tr>

        <tr >   
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            First Name:
          </td>
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
           <input type="text" name="firstName" id="firstName" placeholder="First Name" style="font-size: 25px;"
           v-model="form.billToFirstName">
          </td>
        </tr>
          <tr >   
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            Last Name:
          </td>
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
           <input type="text" name="lastName" id="lastName" placeholder="Last Name" style="font-size: 25px;"
           v-model="form.billToLastName">
          </td>
        </tr>

         <tr >   
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            Address1:
          </td>
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
           <input type="text" name="address1" id="address1"  style="font-size: 25px;"
           v-model="form.billAddress1">
          </td>
        </tr>

        <tr >
              <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            Address2:
             </td>
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
           <input type="text" name="address2" id="address2"  style="font-size: 25px;"
           v-model="form.billAddress2">
          </td>
        </tr>

        <tr >   
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            City:
          </td>
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
           <input type="text" name="city" id="city"  style="font-size: 25px;"
           v-model="form.billCity">
          </td>
        </tr>
        <tr >   
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            State:
          </td>
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
           <input type="text" name="state" id="state"  style="font-size: 25px;"
           v-model="form.billState">
          </td>
        </tr>

        <tr >   
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            Zip:
          </td>
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
           <input type="text" name="zip" id="zip"  style="font-size: 25px;" 
           v-model="form.billZip">
          </td>
        </tr>
        <tr >   
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            Country:
          </td>
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
           <input type="text" name="country" id="country"  style="font-size: 25px;"
           v-model="form.billCountry">
          </td>
        </tr>
        <!-- 勾选shoping address -->
         <tr v-if="checked1">   
          <td style="font-weight: bold; border: 1px solid white;text-align: left;font-size: 25px;"
          colspan="2">
            Shopping Address
          </td>
        </tr>
          <tr v-if="checked1">   
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            First Name:
          </td>
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
           <input type="text" name="shopfirstName" id="shopfirstName" placeholder="First Name" style="font-size: 25px;"
           v-model="form.shipToFirstName">
          </td>:
        </tr>
          <tr v-if="checked1">   
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            Last Name:
          </td>
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
           <input type="text" name="shoplastName" id="shoplastName" placeholder="Last Name" style="font-size: 25px;"
           v-model="form.shipToLastName">
          </td>:
        </tr>

         <tr v-if="checked1">   
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            Address1:
          </td>
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
           <input type="text" name="shopaddress1" id="shopaddress1"  style="font-size: 25px;"
           v-model="form.shipAddress1">
          </td>
        </tr>

        <tr v-if="checked1">
              <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            Address2:
             </td>
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
           <input type="text" name="shopaddress2" id="shopaddress2"  style="font-size: 25px;"
           v-model="form.shipAddress2">
          </td>
        </tr>

        <tr v-if="checked1">   
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            City:
          </td>
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
           <input type="text" name="shopcity" id="shopcity"  style="font-size: 25px;"
           v-model="form.shipCity">
          </td>
        </tr>
        <tr v-if="checked1">   
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            State:
          </td>
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
           <input type="text" name="shopstate" id="shopstate"  style="font-size: 25px;"
           v-model="form.shipState">
          </td>
        </tr>

        <tr v-if="checked1">   
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            Zip:
          </td>
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
           <input type="text" name="shopzip" id="shopzip"  style="font-size: 25px;"
           v-model="form.shipZip">
          </td>
        </tr>
        <tr v-if="checked1">   
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
            Country:
          </td>
          <td style="border: 1px solid white;text-align: left;font-size: 25px;">
           <input type="text" name="shopcountry" id="shopcountry"  style="font-size: 25px;"
           v-model="form.shipCountry">
          </td>
        </tr>
        <!-- 勾选shipping adresss -->
        <tr >
         <td style="border: 1px solid white;text-align: left;font-size: 25px;" colspan="2">
            <el-checkbox v-model="checked1" >
              Ship to different address...
            </el-checkbox>
         </td>
        </tr>
      </tbody>
    </table>
     <el-button type="success" @click="submitOrder">Submit</el-button>
  </div>
  <!--购物车底部组件-->
  <div id="CartBottom">
    <cartbottom />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import catrtop from '../components/CartPageTop.vue';
import cartbottom from '../components/CartPageBottom.vue';
import axios from 'axios';
import apiClient from '@/api/api';
import router from '../router';
// 变量
const checked1 = ref(false);


// 过滤空数据的函数
// 为了修复参数“obj”隐式具有“any”类型的问题，我们为其指定一个明确的类型，这里使用 Record<string, any> 表示一个键为字符串，值为任意类型的对象。
const filterEmptyData = (obj: Record<string, any>) => {
  const newObj = {};
  for (const [key, value] of Object.entries(obj)) {
    if (value!== null && value!== undefined && value!== '') {
      // 为了修复该问题，需要给 newObj 指定一个明确的类型，这里使用 Record<string, any> 表示一个键为字符串，值为任意类型的对象。
      const typedNewObj = newObj as Record<string, any>;
      typedNewObj[key] = value;
    }
  }
  return newObj;
};
// 表单数据
const form = reactive({
 
  cardType: '',             // 信用卡类型
  creditCard: '',           // 信用卡号
  expireDate: '',           // 到期日

  billToFirstName: '',      // 账单姓
  billToLastName: '',       // 账单名
  billAddress1: '',         // 账单地址1
  billAddress2: '',         // 账单地址2
  billCity: '',             // 账单城市
  billState: '',            // 账单州/省
  billZip: '',              // 账单邮编
  billCountry: '',          // 账单国家

  shipToFirstName: '',      // 收货人姓
  shipToLastName: '',       // 收货人名
  shipAddress1: '',         // 收货地址1
  shipAddress2: '',         // 收货地址2
  shipCity: '',             // 收货城市
  shipState: '',            // 收货州/省
  shipZip: '',              // 收货邮编
  shipCountry: '',          // 收货国家

  courier: '',              // 快递方式
  totalPrice: '',           // 总金额
  locale: ''                // 区域
});
// 订单号
const orderId = ref<number | null>(null);

const submitOrder = async () => {
  try {
    // 1. 先调用后端初始化订单（返回订单ID）
    const initResponse = await apiClient.put('/order')
    const newOrderId = initResponse.data;
    console.log('Order initialized with ID:', newOrderId);
    if (!newOrderId) {
      console.error('Failed to initialize order');
      return;
    }
    orderId.value = newOrderId.data;

    // 2. 构建请求体，全部表单数据
    const payload = {
  cardType: form.cardType,
  creditCard: form.creditCard,
  expireDate: form.expireDate,
  billToFirstName: form.billToFirstName,
  billToLastName: form.billToLastName,
  billAddress1: form.billAddress1,
  billAddress2: form.billAddress2,
  billCity: form.billCity,
  billState: form.billState,
  billZip: form.billZip,
  billCountry: form.billCountry,
};

// 如果勾选了 shipping address 复选框，添加 shipping 信息
if (checked1.value) {
  Object.assign(payload, {
    shipToFirstName: form.shipToFirstName,
    shipToLastName: form.shipToLastName,
    shipAddress1: form.shipAddress1,
    shipAddress2: form.shipAddress2,
    shipCity: form.shipCity,
    shipState: form.shipState,
    shipZip: form.shipZip,
    shipCountry: form.shipCountry,
  });
}
    // 过滤空数据
    const filteredPayload = filterEmptyData(payload);

    console.log('Payload to submit:', payload);
    console.log('orderID:',orderId.value);
    // 打印一下 filteredPayload 看是否是纯 JSON
    console.log('Sending payload:', filteredPayload);
    // 4. 发送表单数据到后端接口
    const response = await axios.post(`/api/order/${orderId.value}`,  filteredPayload,
       {
  headers: {
    'Authorization': localStorage.getItem('token'),
    'Content-Type': 'application/json'
  } }
    );
    console.log('Order submitted successfully:', response.data);

    // 5. 处理响应（例如跳转到成功页或弹窗）
    alert('订单提交成功！');
    //跳转订单详情页面,携带订单数据
    //打印数据
  console.log('order detail:',response.data);
 
  //获取详细数据，两部分数据，一部分是订单数据，一部分是订单详情数据
  const orderData = response.data.data.orders;
  const lineItems = response.data.data.lineItemVos;
  // 打印订单主信息
  console.log('订单信息:', orderData);

  // 打印每个商品信息
  // 为参数 item 和 index 显式指定类型
  lineItems.forEach((item: { lineItem: any; orderStatus: any }, index: number) => {
    console.log(`商品 ${index + 1}:`, item.lineItem);
    console.log(`状态 ${index + 1}:`, item.orderStatus);
  });

    router.push({
    path: '/orderconfirm',
    query: {
      orderData: encodeURIComponent(JSON.stringify(orderData)),
      lineItems: encodeURIComponent(JSON.stringify(lineItems))
    }
  });

  } catch (error) {
    console.error('Error submitting order:', error);
    alert('订单提交失败，请重试！');
  }
  
};

</script>
<style scoped>
#Catalog {
  
  margin-bottom: 15vh;

}

table {
  color: black;
}

.double-col {
  flex-wrap: wrap;
}
</style>